<template>
  <div class="page-container">
    <van-nav-bar 
      title="规则分组管理" 
      left-arrow 
      @click-left="router.back()"
    >
      <template #right>
        <van-icon name="plus" @click="showCreateGroupDialog = true" />
      </template>
    </van-nav-bar>

    <div class="content">
      <!-- 分组树形结构 -->
      <van-cell-group inset title="规则分组">
        <div v-for="group in groupTree" :key="group.id" class="group-tree">
          <!-- 顶级分组 -->
          <van-cell 
            :title="group.groupName" 
            :label="group.description"
            is-link
            @click="toggleGroup(group)"
          >
            <template #icon>
              <van-icon :name="group.expanded ? 'arrow-down' : 'arrow'" />
            </template>
            <template #extra>
              <div class="group-actions">
                <van-icon name="edit" @click.stop="editGroup(group)" />
                <van-icon name="delete" @click.stop="deleteGroup(group)" />
              </div>
            </template>
          </van-cell>

          <!-- 子分组 -->
          <div v-if="group.expanded && group.children && group.children.length > 0" class="sub-groups">
            <van-cell 
              v-for="child in group.children" 
              :key="child.id"
              :title="child.groupName"
              :label="child.description"
              class="sub-group-cell"
            >
              <template #extra>
                <div class="group-actions">
                  <van-icon name="edit" @click="editGroup(child)" />
                  <van-icon name="delete" @click="deleteGroup(child)" />
                </div>
              </template>
            </van-cell>
          </div>

          <!-- 添加子分组按钮 -->
          <van-cell 
            v-if="group.expanded"
            title="+ 添加子分组" 
            class="add-sub-group"
            @click="addSubGroup(group)"
          />
        </div>
      </van-cell-group>
    </div>

    <!-- 创建/编辑分组弹窗 -->
    <van-dialog
      v-model:show="showGroupDialog"
      :title="isEditMode ? '编辑分组' : '新建分组'"
      show-cancel-button
      @confirm="saveGroup"
    >
      <div class="dialog-content">
        <van-field
          v-model="groupForm.groupName"
          label="分组名称"
          placeholder="请输入分组名称"
          required
        />
        
        <van-field
          v-model="groupForm.description"
          label="分组描述"
          type="textarea"
          placeholder="请输入分组描述"
          rows="3"
        />
        
        <van-field
          v-if="groupForm.groupLevel === 2"
          v-model="parentGroupName"
          label="父分组"
          placeholder="请选择父分组"
          readonly
          is-link
          @click="showParentGroupPicker = true"
        />
      </div>
    </van-dialog>

    <!-- 父分组选择器 -->
    <van-popup v-model:show="showParentGroupPicker" position="bottom">
      <van-picker
        :columns="parentGroupOptions"
        @confirm="onParentGroupConfirm"
        @cancel="showParentGroupPicker = false"
      />
    </van-popup>

    <!-- 创建分组快捷按钮 -->
    <van-dialog
      v-model:show="showCreateGroupDialog"
      title="选择分组类型"
      show-cancel-button
      @confirm="confirmCreateGroup"
    >
      <div class="create-group-options">
        <van-radio-group v-model="createGroupType">
          <van-cell-group>
            <van-cell title="顶级分组" clickable @click="createGroupType = 'top'">
              <template #right-icon>
                <van-radio name="top" />
              </template>
            </van-cell>
            <van-cell title="子分组" clickable @click="createGroupType = 'sub'">
              <template #right-icon>
                <van-radio name="sub" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { dataControlApi } from '@/api'

const router = useRouter()

// 响应式数据
const groupTree = ref([])
const showGroupDialog = ref(false)
const showCreateGroupDialog = ref(false)
const showParentGroupPicker = ref(false)
const isEditMode = ref(false)
const createGroupType = ref('top')

// 表单数据
const groupForm = reactive({
  id: null,
  groupName: '',
  description: '',
  parentId: null,
  groupLevel: 1
})

const parentGroupName = ref('')

// 计算属性
const parentGroupOptions = computed(() => {
  return groupTree.value.map(group => ({
    text: group.groupName,
    value: group.id
  }))
})

// 加载分组树
const loadGroupTree = async () => {
  try {
    const tree = await dataControlApi.getGroupTree()
    // 为每个分组添加展开状态
    groupTree.value = tree.map(group => ({
      ...group,
      expanded: false
    }))
  } catch (error) {
    showToast('加载失败: ' + error.message)
  }
}

// 切换分组展开状态
const toggleGroup = (group) => {
  group.expanded = !group.expanded
}

// 编辑分组
const editGroup = (group) => {
  isEditMode.value = true
  groupForm.id = group.id
  groupForm.groupName = group.groupName
  groupForm.description = group.description
  groupForm.parentId = group.parentId
  groupForm.groupLevel = group.groupLevel
  
  // 设置父分组名称
  if (group.parentId) {
    const parentGroup = groupTree.value.find(g => g.id === group.parentId)
    parentGroupName.value = parentGroup ? parentGroup.groupName : ''
  } else {
    parentGroupName.value = ''
  }
  
  showGroupDialog.value = true
}

// 删除分组
const deleteGroup = async (group) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除分组"${group.groupName}"吗？`
    })
    
    await dataControlApi.deleteGroup(group.id)
    showToast('删除成功')
    loadGroupTree()
  } catch (error) {
    if (error !== 'cancel') {
      showToast('删除失败: ' + error.message)
    }
  }
}

// 添加子分组
const addSubGroup = (parentGroup) => {
  isEditMode.value = false
  resetGroupForm()
  groupForm.parentId = parentGroup.id
  groupForm.groupLevel = 2
  parentGroupName.value = parentGroup.groupName
  showGroupDialog.value = true
}

// 确认创建分组类型
const confirmCreateGroup = () => {
  isEditMode.value = false
  resetGroupForm()
  
  if (createGroupType.value === 'top') {
    groupForm.groupLevel = 1
    groupForm.parentId = null
    parentGroupName.value = ''
  } else {
    groupForm.groupLevel = 2
    // 需要选择父分组
    if (groupTree.value.length === 0) {
      showToast('请先创建顶级分组')
      return
    }
  }
  
  showCreateGroupDialog.value = false
  showGroupDialog.value = true
}

// 父分组选择确认
const onParentGroupConfirm = ({ selectedOptions }) => {
  groupForm.parentId = selectedOptions[0].value
  parentGroupName.value = selectedOptions[0].text
  showParentGroupPicker.value = false
}

// 保存分组
const saveGroup = async () => {
  // 验证
  if (!groupForm.groupName.trim()) {
    showToast('请输入分组名称')
    return
  }
  
  if (groupForm.groupLevel === 2 && !groupForm.parentId) {
    showToast('请选择父分组')
    return
  }
  
  try {
    if (isEditMode.value) {
      await dataControlApi.updateGroup(groupForm.id, groupForm)
      showToast('更新成功')
    } else {
      await dataControlApi.createGroup(groupForm)
      showToast('创建成功')
    }
    
    showGroupDialog.value = false
    loadGroupTree()
  } catch (error) {
    showToast('保存失败: ' + error.message)
  }
}

// 重置表单
const resetGroupForm = () => {
  groupForm.id = null
  groupForm.groupName = ''
  groupForm.description = ''
  groupForm.parentId = null
  groupForm.groupLevel = 1
  parentGroupName.value = ''
}

onMounted(() => {
  loadGroupTree()
})
</script>

<style scoped>
.content {
  padding: 16px;
}

.group-tree {
  margin-bottom: 8px;
}

.sub-groups {
  margin-left: 20px;
  border-left: 2px solid #ebedf0;
}

.sub-group-cell {
  background-color: #f7f8fa;
}

.add-sub-group {
  margin-left: 20px;
  color: #1989fa;
  font-size: 14px;
}

.group-actions {
  display: flex;
  gap: 12px;
}

.group-actions .van-icon {
  font-size: 16px;
  color: #969799;
}

.group-actions .van-icon:hover {
  color: #1989fa;
}

.dialog-content {
  padding: 16px;
}

.dialog-content .van-field {
  margin-bottom: 12px;
}

.create-group-options {
  padding: 16px;
}

.van-cell-group {
  margin-bottom: 16px;
}
</style>
